package logic

import (
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"net/http"
	"path"
	"runtime"
	"strconv"
	"strings"
	"tiktok/dao"
	"tiktok/models"
	"tiktok/web"
)

func FriendList(ctx *gin.Context) {
	//获取当前文件名
	_, fullFilename, _, _ := runtime.Caller(0)
	fileName := path.Base(fullFilename)

	//在函数退出前，执行defer
	//捕捉异常后，程序不会异常退出
	defer func() {
		err := recover() //内置函数，可以捕捉到函数异常
		if err != nil {
			logrus.Error(fileName + GetFollowErr)
		}
	}()

	token := ctx.Query("token")
	db := dao.GetDB(ctx)
	uid := ctx.Query("user_id")

	//token解析
	user, err := web.ParseToken(token)
	if err != nil { //解析token失败
		logrus.Error(ParseTokenErr)
		ctx.JSON(http.StatusBadRequest,
			models.Status{
				StatusCode: -1,
				StatusMsg:  ServerErr,
			})
		return
	}
	uid = strconv.FormatInt(user.Uid, 10)

	//查询关注列表
	var followList UserList
	db.Table("tiktok_user").Select("follow_list").Where("uid = ?", uid).Find(&followList.UserList)

	//查询粉丝列表
	var followerList UserList
	db.Table("tiktok_user").Select("follower_list").Where("uid = ?", uid).Find(&followerList.UserList)

	//定义真正要返回的，存储好友的列表
	friendList := make([]models.User, 0, 256)

	//对关注字符串和粉丝字符串分隔
	str := followList.UserList
	sliceFollow := strings.Split(str, "/")
	str = followerList.UserList

	//循环遍历
	for i := 1; i < len(sliceFollow)-1; i++ {
		strFollow := "/" + sliceFollow[i] + "/"
		if strings.Contains(str, strFollow) {
			var user models.User
			parseIntFollow, err := strconv.ParseInt(sliceFollow[i], 10, 64)
			if err != nil {
				ctx.JSON(http.StatusOK, models.Status{
					StatusCode: -1,
					StatusMsg:  ParseErr,
				})
			}
			db.Take(&user, parseIntFollow)

			user.IsFollow = true
			friendList = append(friendList, user)
		}
	}

	ctx.JSON(http.StatusOK, followListMsg{
		Status: models.Status{
			StatusCode: 0,
			StatusMsg:  SelectSuccess,
		},
		UserList: friendList,
	})
}
